package com.dss.auto_deploy.util;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * @Description:
 * @author: dongshoushan
 * @date: 2023年10月13日 11:05
 */
public class ExecutorUtils {
    public static void shutdownThread(ThreadPoolTaskExecutor executor, List<CompletableFuture<?>> queryTasks) {
        // 获取所有正在运行的线程
        Set<Thread> threads = Thread.getAllStackTraces().keySet();
        // 遍历线程池中的线程，中断并移除需要销毁的线程
        for (Thread thread : threads) {
            if (thread.getName().startsWith("dss-")) { // 以"dss-"开头为需要销毁的线程
                boolean isUsed = false;
                for (CompletableFuture<?> queryTask : queryTasks) {
                    if (!queryTask.isDone() || queryTask.isCompletedExceptionally()) {
                        isUsed = true;
                        break;
                    }
                }
                if (!isUsed) {
                    thread.interrupt();
                    executor.getThreadPoolExecutor().remove(thread);
                    //System.out.println("销毁线程"+thread);
                }
            }
        }
    }
}
